/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 *
 * 我的工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    Image,
    TouchableOpacity,
    ScrollView,
    Modal, Platform, BackHandler, ToastAndroid
} from 'react-native';
import {connect} from 'react-redux';
import {COLOR_LINK, COLOR_WHITE, FONT_COLOR_SUB_TITLE} from "../../../constant/PHColors"
import {styles} from './RoomStatusScreen.Style'
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import AntDesign from "react-native-vector-icons/AntDesign";
import BottomButtonView_room from "../../../component/BottomButtonView/BottomButtonView_room";
import BottomButtonList from "../../../component/BottomButtonView/BottomButtonList";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import {retrieveRoomMSG} from "./Actions";
import LoadingView from "../../../component/LoadingView/LoadingView";
import {Action} from "../../../configuration/ActionCreator";
import Sound from "react-native-sound";
import {AppRequestPath} from "../../../configuration/AppConfig";

class RoomStatusScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: `客房状态`,
    });

    // 构造
    constructor(props) {
        super(props);

        // 初始状态
        this.state = {
            buttonList:{},
            ho_guest:{},
            order_sweep:{},
            whsk_order:{},
            authority:this.props.navigation.getParam("authority")?this.props.navigation.getParam("authority"):'',       //'清洁人'或'检查人'
            room:this.props.navigation.getParam("room"),                                //房号
            button:this.props.navigation.getParam("button")==='yes'?'yes':'no',       //是否显示按钮
            orderid:this.props.navigation.getParam("orderid")?this.props.navigation.getParam("orderid"):'',                         //orderid(暂时的)
            procedure:this.props.navigation.getParam("orderid")===""?"WHSKRetrieveOrder":"WHSKRetrieveOrder",     //WHSKRetrieveRoomMsg
            linenAndBar:{},                             //布草数组
            checkUnusual:{},                            //查房数组
            goodsAndServices :[],       //服务物品输送
            soundState_c:'点击播放',
        };

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onRetrieveRoomMSG !== this.props.onRetrieveRoomMSG && nextProps.onRetrieveRoomMSG.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveRoomMSG.RETURN === ReturnStatus.Success) {
                // this.props.navigation.state.params.callBack();

                let checkUnusual = {};
                let linenAndBar = {};
                let goodsAndServices = [];
                if(this.state.procedure==="WHSKRetrieveOrder"){
                    nextProps.onRetrieveRoomMSG.whsk_Order_DetailBy.map((item, index) => {
                        if(item.ordertype==="布草/易耗品/酒水补充"){
                            if(linenAndBar[item.orderid]){
                                linenAndBar[item.orderid].push(item)
                            }else{
                                linenAndBar[item.orderid] = [item]
                            }
                        }
                        if(item.ordertype==="查房,查遗留/异常/消费"){
                            if(checkUnusual[item.orderid]){
                                checkUnusual[item.orderid].push(item)
                            }else{
                                checkUnusual[item.orderid] = [item]
                            }
                        }
                        if(item.ordertype==="物品/服务输送"||item.ordertype==="住房打扫"||item.ordertype==="消费项目"){
                            goodsAndServices.push(item)
                        }
                    })
                }

                this.setState({
                    ho_guest:nextProps.onRetrieveRoomMSG.ho_guest.length===0?{}:nextProps.onRetrieveRoomMSG.ho_guest[0],
                    order_sweep:nextProps.onRetrieveRoomMSG['order_sweep'].length>0?nextProps.onRetrieveRoomMSG.order_sweep[0]:{},
                    whsk_order:nextProps.onRetrieveRoomMSG['whsk_order']?nextProps.onRetrieveRoomMSG.whsk_order[0]:{},
                    checkUnusual:checkUnusual,
                    linenAndBar:linenAndBar,
                    goodsAndServices:goodsAndServices,
                })
            } else {
                // dispatch(doDisplayWarnMessage(nextProps.onRetrieveRoomMSG.MSG))
            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {"arg":{"orderid":this.state.orderid,"room":this.state.room}}
        dispatch(retrieveRoomMSG(JSON.stringify(str),this.state.procedure))
    }

    componentWillMount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    onBackAndroid = () =>{
        if(this.props.navigation.isFocused() && this.props.navigation.state.routeName==="RoomStatusScreen"){//判断   该页面是否处于聚焦状态
            this.props.navigation.state.params.callBack();
        }
    };

    // componentWillUnmount() {
    //     if (Platform.OS === 'android'||Platform.OS==='ios') {
    //         this.props.navigation.state.params.callBack()
    //     }
    // };

    render() {
        let {onRetrieveRoomMSG} = this.props;
        let _this = this;
        if (onRetrieveRoomMSG.fetchStatus === FetchStatus.Success) {
            return (
                <SafeAreaView style={styles.body}>

                    <ScrollView style={styles.body}>
                        {/*房号信息*/}
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {

                        }}>
                            <View style={[styles.container]}>

                                <View style={styles.iconBox}>
                                    <FontAwesome name={'hotel'} size={20} style={{color: 'black'}}/>
                                </View>

                                <View style={styles.textBox}>
                                    <View style={styles.leftBox}>
                                        <Text style={styles.text}>
                                            {this.state.room}
                                        </Text>
                                        {
                                            (this.state.ho_guest['status_c'])
                                            ?(
                                                <Text style={styles.text}>
                                                    【{this.state.ho_guest.status_c}】
                                                </Text>
                                            ) :(
                                                <Text style={styles.text}>
                                                </Text>
                                            )
                                        }

                                    </View>
                                </View>

                            </View>
                        </TouchableOpacity>

                        {/*清洁信息*/}
                        {
                            (this.state.procedure==="WHSKRetrieveOrder")
                            &&
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}>
                                    <View style={[styles.container,{marginTop:2}]}>

                                        <View style={styles.iconBox}>
                                            <FontAwesome name={'hourglass-2'} size={20} style={{color: 'black'}}/>
                                        </View>

                                        <View style={styles.textBox}>
                                            <View style={styles.leftBox}>
                                                {
                                                    (this.state.whsk_order['status'])
                                                        ?(
                                                            <Text style={styles.text}>
                                                                {this.state.whsk_order.status}
                                                            </Text>
                                                        ) :(
                                                            <Text style={styles.text}>
                                                            </Text>
                                                        )
                                                }
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        }


                        {
                            (this.state.whsk_order['status'] && this.state.whsk_order.status==="不通过检查")
                            &&
                            (


                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                    }}>
                                        <View style={[styles.container,{height:30}]}>
                                            <View style={styles.leftBox}>
                                                <Text style={[styles.text,{color:'#6b6b6b',marginLeft:50,marginTop:3}]}>
                                                    原因:
                                                </Text>
                                                <Text style={[styles.text,{color:'#6b6b6b',marginLeft:2,marginTop:3}]}>
                                                    {this.state.whsk_order.remark}
                                                </Text>
                                            </View>
                                        </View>
                                    </TouchableOpacity>

                            )
                        }

                        {
                            ((this.state.whsk_order['status'] && this.state.whsk_order.status==="不通过检查") &&  (this.state.whsk_order.hasOwnProperty("sound") && this.state.whsk_order.sound!==""))
                            &&
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                    // {this.state.whsk_order.sound}
                                    let url = AppRequestPath().replace("qms/mobile","")+"attach/"+this.state.whsk_order.sound
                                    console.log(url)
                                    let whoosh = new Sound(url, '', (err) => {
                                        this.setState({soundState_c:"正在播放..."})
                                        if(err) {
                                            this.setState({soundState_c:"播放失败"})
                                            return console.log(err)
                                        }
                                        whoosh.play(success => {
                                            if(success) {
                                                this.setState({soundState_c:"点击播放"})
                                                console.log('success - 播放成功')
                                            }else {
                                                this.setState({soundState_c:"播放失败"})
                                                console.log('fail - 播放失败')
                                            }
                                        })
                                    })
                                }}>
                                    <View style={[styles.container,{height:30}]}>
                                        <View style={styles.leftBox}>
                                            <Text style={[styles.text,{color:'#6b6b6b',marginLeft:50,marginTop:3}]}>
                                                语音备注:
                                            </Text>
                                            <Text style={[styles.text,{color:COLOR_LINK,marginLeft:2,marginTop:3}]}>
                                                {this.state.soundState_c}
                                            </Text>
                                        </View>
                                    </View>
                                </TouchableOpacity>

                            )
                        }

                        {/*客人*/}
                        <TouchableOpacity activeOpacity={0.8} onPress={() => {

                        }}>
                            <View style={[styles.container,{marginTop:2}]}>

                                <View style={styles.iconBox}>
                                    <FontAwesome name={'user-o'} size={20} style={{color: 'black'}}/>
                                </View>

                                <View style={styles.textBox}>
                                    <View style={styles.leftBox}>
                                        <Text style={styles.text}>
                                            {
                                                (this.state.ho_guest['gname'])?(<Text>{this.state.ho_guest.gname}</Text>):'当前无客人'
                                            }
                                        </Text>
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>

                        {/*备注*/}
                        {
                            (this.state.ho_guest['gname']&&this.state.ho_guest['msg']!=="")
                            &&
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}>
                                    <View style={[styles.container, {marginTop: 2}]}>

                                        <View style={styles.iconBox}>
                                            <AntDesign name={'profile'} size={20} style={{color: 'black'}}/>
                                        </View>

                                        <View style={styles.textBox}>
                                            <View style={styles.leftBox}>
                                                {
                                                    (this.state.ho_guest['msg'])
                                                        ? (
                                                            <Text style={styles.text}>
                                                                {this.state.ho_guest.msg}
                                                            </Text>
                                                        ) : (
                                                            <Text style={styles.text}>
                                                            </Text>
                                                        )
                                                }
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        }


                        {
                            (this.state.ho_guest['gname'])
                            &&
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}>
                                    <View style={[styles.container,{marginTop:2}]}>

                                        <View style={styles.iconBox}>
                                            <AntDesign name={'clockcircleo'} size={20} style={{color: 'black'}}/>
                                        </View>

                                        <View style={styles.textBox}>
                                            <View style={styles.leftBox}>
                                                <Text style={styles.text}>
                                                    抵离店：
                                                    {
                                                        (this.state.ho_guest['arr_d_c'])?(<Text>{this.state.ho_guest.arr_d_c}</Text>):''
                                                    }
                                                    －
                                                    {
                                                        (this.state.ho_guest['exp_dep_d_c'])?(<Text>{this.state.ho_guest.exp_dep_d_c}</Text>):''
                                                    }
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        }

                        {/*{
                            (this.state.ho_guest['gname'])
                            &&
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}>
                                    <View style={[styles.container,{marginTop:2}]}>

                                        <View style={styles.iconBox}>
                                            <AntDesign name={'clockcircleo'} size={20} style={{color: 'black'}}/>
                                        </View>

                                        <View style={styles.textBox}>
                                            <View style={styles.leftBox}>
                                                <Text style={styles.text}>
                                                    {
                                                        (this.state.ho_guest['exp_dep_d_c'])?(<Text>离店：{this.state.ho_guest.exp_dep_d_c}</Text>):''
                                                    }
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        }*/}

                        {
                            (this.state.whsk_order['ordertype'] && (this.state.whsk_order.ordertype==="物品/服务输送" || this.state.whsk_order.ordertype==="住房打扫" || this.state.whsk_order.ordertype==="消费项目"))
                            &&
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}>
                                    <View style={[styles.container,{marginTop:2}]}>

                                        <View style={styles.iconBox}>
                                            <FontAwesome name={'cube'} size={20} style={{color: 'black'}}/>
                                        </View>

                                        <View style={styles.textBox}>
                                            <View style={styles.leftBox}>
                                                <Text style={styles.text}>
                                                    {
                                                        this.render_goodsAndServices()
                                                    }
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                        }

                        {
                            ( this.state.whsk_order['remark'] )
                            ?
                            (
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {

                                }}>
                                    <View style={[styles.container,{marginTop:2}]}>

                                        <View style={styles.iconBox}>
                                            <AntDesign name={'tag'} size={20} style={{color: 'black'}}/>
                                        </View>

                                        <View style={styles.textBox}>
                                            <View style={styles.leftBox}>
                                                <Text style={styles.text}>
                                                    备注：
                                                    {
                                                        (this.state.whsk_order['remark'])?(<Text>{this.state.whsk_order.remark}</Text>):''
                                                    }
                                                </Text>
                                            </View>
                                        </View>
                                    </View>
                                </TouchableOpacity>
                            )
                            :(
                                <View>

                                </View>
                            )
                        }

                        {
                            (this.state.procedure==="WHSKRetrieveOrder")
                            &&
                            (
                                <View>
                                    {/*查房，查遗留/异常/消费*/}
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        if(Object.keys(this.state.checkUnusual).length > 0){
                                            this.props.navigation.navigate('addCheckUnusualResultScreen',{place:this.state.room,orderid:this.state.orderid,orderpid:this.state.order_sweep['orderpid']?this.state.order_sweep['orderpid']:'',gno:this.state.ho_guest.gno,callBack:()=>_this.freshScreen(),resultJson:this.state.checkUnusual });
                                        }else{
                                            this.props.navigation.navigate('addCheckUnusualScreen',{place:this.state.room,orderid:this.state.orderid,orderpid:this.state.order_sweep['orderpid']?this.state.order_sweep['orderpid']:'',gno:this.state.ho_guest.gno,callBack:()=>_this.freshScreen()});
                                        }
                                    }}>
                                        <View style={[styles.container,{marginTop:10}]}>

                                            <View style={styles.iconBox}>
                                                <FontAwesome name={'glass'} size={20} style={{color: '#6ba1f9'}}/>
                                            </View>

                                            <View style={styles.textBox}>
                                                <View style={styles.leftBox}>
                                                    <Text style={styles.text}>
                                                        查房,查遗留/异常/消费
                                                    </Text>
                                                </View>
                                                {
                                                    Object.keys(this.state.checkUnusual).length > 0 &&
                                                    <View style={styles.rightBox}>
                                                        <Text style={styles.numText}>
                                                            {Object.keys(this.state.checkUnusual).length}
                                                        </Text>
                                                    </View>
                                                }
                                            </View>

                                            <View style={styles.arrowBox}>
                                                <AntDesign name={'right'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                            </View>
                                        </View>
                                    </TouchableOpacity>

                                    {/*布草、易耗品*/}
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        if(Object.keys(this.state.linenAndBar).length > 0){
                                            this.props.navigation.navigate('addLinenAndBarResultScreen',{place:this.state.room,orderid:this.state.orderid,orderpid:this.state.order_sweep['orderpid']?this.state.order_sweep['orderpid']:'',gno:this.state.ho_guest.gno,callBack:()=>_this.freshScreen(),resultJson:this.state.linenAndBar });
                                        }else{
                                            this.props.navigation.navigate('addLinenAndBarScreen',{place:this.state.room,orderid:this.state.orderid,orderpid:this.state.order_sweep['orderpid']?this.state.order_sweep['orderpid']:'',gno:this.state.ho_guest.gno,callBack:()=>_this.freshScreen()});
                                        }
                                    }}>
                                        <View style={[styles.container,{marginTop:2}]}>

                                            <View style={styles.iconBox}>
                                                <FontAwesome name={'glass'} size={20} style={{color: '#6ba1f9'}}/>
                                            </View>

                                            <View style={styles.textBox}>
                                                <View style={styles.leftBox}>
                                                    <Text style={styles.text}>
                                                        布草/易耗品/酒水补充
                                                    </Text>
                                                </View>
                                                {
                                                    Object.keys(this.state.linenAndBar).length > 0 &&
                                                    <View style={styles.rightBox}>
                                                        <Text style={styles.numText}>
                                                            {Object.keys(this.state.linenAndBar).length}
                                                        </Text>
                                                    </View>
                                                }
                                            </View>

                                            <View style={styles.arrowBox}>
                                                <AntDesign name={'right'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                            </View>
                                        </View>
                                    </TouchableOpacity>

                                    {/*工程维修
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        this.props.navigation.navigate('RoomRepariRecordScreen',{ds:this.state.ho_guest});
                                    }}>
                                        <View style={[styles.container,{marginTop:2}]}>

                                            <View style={styles.iconBox}>
                                                <FontAwesome name={'wrench'} size={20} style={{color: '#6ba1f9'}}/>
                                            </View>

                                            <View style={styles.textBox}>
                                                <View style={styles.leftBox}>
                                                    <Text style={styles.text}>
                                                        工程维修
                                                    </Text>
                                                </View>
                                                {
                                                    this.props.num > 0 &&
                                                    <View style={styles.rightBox}>
                                                        <Text style={styles.numText}>
                                                            {this.props.num}
                                                        </Text>
                                                    </View>
                                                }
                                            </View>

                                            <View style={styles.arrowBox}>
                                                <AntDesign name={'right'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                            </View>
                                        </View>
                                    </TouchableOpacity>*/}

                                    {/*房间详情*/}
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        // this.props.navigation.navigate('RoomRepariRecordScreen',{ds:this.state.ho_guest});
                                        // let authority = '清洁人';
                                        // if(item.status==="完成清洁"){
                                        //     authority = '检查人';
                                        // }
                                        this.props.navigation.navigate('orderInfo',{room:this.state.room,hsk_status:this.state.hsk_status,button:'yes',authority:this.state.authority,orderid:'',callBack:()=>{

                                            }});
                                    }}>
                                        <View style={[styles.container,{marginTop:2}]}>

                                            <View style={styles.iconBox}>
                                                <FontAwesome name={'home'} size={20} style={{color: '#6ba1f9'}}/>
                                            </View>

                                            <View style={styles.textBox}>
                                                <View style={styles.leftBox}>
                                                    <Text style={styles.text}>
                                                        房间详情
                                                    </Text>
                                                </View>
                                                {
                                                    this.props.num > 0 &&
                                                    <View style={styles.rightBox}>
                                                        <Text style={styles.numText}>
                                                            {this.props.num}
                                                        </Text>
                                                    </View>
                                                }
                                            </View>

                                            <View style={styles.arrowBox}>
                                                <AntDesign name={'right'} size={18} style={{color: FONT_COLOR_SUB_TITLE}}/>
                                            </View>
                                        </View>
                                    </TouchableOpacity>

                                </View>
                            )
                        }


                        <View style={{marginTop:10,marginRight: 15 ,flexDirection: 'row',alignItems: 'center',justifyContent: 'flex-end',}}>
                            <Text style={styles.text}>
                                {this.state.ho_guest.room_c}
                            </Text>
                        </View>

                    </ScrollView>

                    {
                        (this.state.button==='yes')
                        &&
                        (
                            this.init_button()
                        )
                    }


                </SafeAreaView>
            )
        }else{
            return <LoadingView/>
        }

    }

    render_goodsAndServices = ()=>{
        let goods = '';
        for(let x in this.state.goodsAndServices){
            if(this.state.goodsAndServices[x]['ordertype']==="住房打扫"){
                goods += this.state.goodsAndServices[x]['info_detail'].replace("X1",'') + "   " + this.state.goodsAndServices[x]['comment']
            }else{
                goods += this.state.goodsAndServices[x]['info_detail']
            }

        }
        return (
            <Text>{goods}</Text>
        )
    }

    init_button=()=>{
        // let operation = ''
        // if(this.state.authority==='清洁人'){
        //     if(this.state.order_sweep.whsk_status==="待清洁"){
        //         operation = '我要清洁,无需清洁'
        //     }else if(this.state.order_sweep.whsk_status==="重新清洁"){
        //         operation = '完成清洁,无需清洁'
        //     }else if(this.state.order_sweep.whsk_status==="开始"){
        //         operation = '完成清洁,无需清洁'
        //     }else if(this.state.order_sweep.whsk_status==="完毕"){
        //         operation = '';
        //         this.setState({
        //             button:'no',
        //         })
        //     }
        // }else if(this.state.authority==='检查人'){
        //     if(this.state.order_sweep.whsk_status==="完毕"){
        //         operation = '通过'
        //     }
        // }

        this.state.buttonList = {}
        this.props.onCacheButton.map((item, index) => {
            if(item.ordertype===this.state.whsk_order.ordertype && item.usertype===this.state.authority && item.status===this.state.whsk_order.status){
                this.state.buttonList = item
            }
        })
        if(JSON.stringify(this.state.buttonList)==='{}'||this.state.buttonList.operation===""){
            return(
                <View>

                </View>
            )
        }else{
            return(
                <BottomButtonList
                    buttonList={this.state.buttonList}
                    dataSource={this.state}
                    orderid={this.state.orderid}
                    $this = {this.props.navigation}
                    dataBack={()=>{
                        this.freshScreen();
                    }}
                />
            )
        }


        // alert(JSON.stringify(this.state.buttonList));



        /*return(
            <BottomButtonView_room
                operation={operation}
                dataSource={this.state}
                orderid={this.state.orderid}
                $this = {this.props.navigation}
                dataBack={()=>{
                    this.freshScreen();
                }}
            />
        )*/
    };

    freshScreen=()=>{
        let {dispatch} = this.props;

        this.props.navigation.navigate('RoomStatusScreen');

        let str = {"arg":{"orderid":this.state.orderid}}
        dispatch(retrieveRoomMSG(JSON.stringify(str),this.state.procedure))
    }

}

const props = state => {
    return {
        onRetrieveRoomMSG:state.onRetrieveRoomMSG,
        onCacheButton: state.onCache.buttonlist,
    }
}

export default RoomStatusScreen = connect(props)(RoomStatusScreen);